package com.asset.salesforce.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.model.Appointment;
import com.asset.salesforce.model.AppointmentData;
import com.asset.salesforce.model.AppointmentDetails;
import com.asset.salesforce.model.AppointmentDetailsList;
import com.asset.salesforce.model.AppointmentList;
import com.asset.salesforce.model.Company;
import com.asset.salesforce.model.Contact;
import com.asset.salesforce.model.Employee;
import com.asset.salesforce.model.Lead;
import com.asset.salesforce.service.AppointmentService;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.CompanyService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.LeadService;

@Controller
public class AppointmentController {

	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private ContactService contactService;
	
	@Autowired
	private AppointmentService appointmentService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private CalendarService calendarService;
	
	@Autowired
	private LeadService leadService;

	//static final Logger logger = Logger.getLogger(AppointmentController.class);
	 
	@RequestMapping(value="/getAllAppointments/{id}", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public AppointmentList getAllAppointments(@PathVariable String id){
		
		//logger.info("get all appointments of a certain lead	>>>>>>>>>>>>>>>>>>>>");
		AppointmentList appointmentList = new AppointmentList();
		List<AppointmentData>appointmentData = new ArrayList<AppointmentData>();
		List<Appointment> appointments =appointmentService.getAppointmentByParentId(Integer.parseInt(id), "lead");
		System.out.println("appointments size>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+appointments.size());
		for (Appointment appointment : appointments) {
			AppointmentData data = new AppointmentData();
			data.setId(appointment.getId());
			if(appointment.getSalesMan()!=null){
				Employee employee = employeeService.getById(appointment.getSalesMan().getId());
				data.setSalesManName(employee.getfName());
			}
			if(appointment.getContactedPerson()!=null){
				Contact contact = contactService.getContactById(appointment.getContactedPerson().getId());
				data.setContactedPersonName(contact.getfName());
			}
			data.setDate(appointment.getDate());
			data.setStartTime(appointment.getTime());
			data.setEndTime(appointment.getMeetingDuration());
			appointmentData.add(data);
		}
		appointmentList.setAppointmentData(appointmentData);
		return appointmentList;
	}
	@RequestMapping(value="/getAllAppointmentsByEmpId/{empId}", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public AppointmentList getAllAppointmentsByEmpId(@PathVariable String empId){
		
		//logger.info("get all appointments of a certain employee	>>>>>>>>>>>>>>>>>>>>");
		Employee employee = employeeService.getById(Integer.parseInt(empId));
		List<Lead>leads = leadService.getLeads(employee.getId());
		AppointmentList appointmentList = new AppointmentList();
		List<AppointmentData>appointmentData = new ArrayList<AppointmentData>();
		for (Lead lead : leads) {
			List<Appointment> appointments = appointmentService.getAppointmentByParentId(lead.getId(), "lead");
			for (Appointment appointment : appointments) {
				AppointmentData data = new AppointmentData();
				data.setId(appointment.getId());
				if(appointment.getSalesMan()!=null){
					Employee salesMan = employeeService.getById(appointment.getSalesMan().getId());
					data.setSalesManName(salesMan.getfName());
				}
				if(appointment.getContactedPerson()!=null){
					Contact contact = contactService.getContactById(appointment.getContactedPerson().getId());
					data.setContactedPersonName(contact.getfName());
				}
				data.setDate(appointment.getDate());
				data.setStartTime(appointment.getTime());
				data.setEndTime(appointment.getMeetingDuration());
				appointmentData.add(data);
			}
			appointmentList.setAppointmentData(appointmentData);
		}		
		return appointmentList;
	}
	@RequestMapping(value="/getAppointment/id={id}/empId={empId}", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public Appointment getAppointment(@PathVariable String id,@PathVariable String empId){
		
		//logger.info("get details for a certain appointment	>>>>>>>>>>>>>>>>>>>>");
		Appointment appointment = appointmentService.getAppointmentById(new Appointment(), Integer.parseInt(id));
		Employee owner = employeeService.getById(Integer.parseInt(empId));
		appointment.setOwnerName(owner.getfName()+" "+owner.getlName());
		if(appointment.getSalesMan()!=null){
			Employee employee = employeeService.getById(appointment.getSalesMan().getId());
			appointment.setSalesManName(employee.getfName());
		}
		if(appointment.getContactedPerson()!=null){
			Contact contact = contactService.getContactById(appointment.getContactedPerson().getId());
			appointment.setContactedPersonName(contact.getfName());
		}
		return appointment;
	}
	@RequestMapping(value="/addAppointmentDetails/{empId}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public AppointmentDetailsList addAppointment(@PathVariable String empId){
		
		//logger.info("get add appointment get method 	>>>>>>>>>>>>>>>>>>>>");
		
		Employee owner = employeeService.getById(Integer.parseInt(empId));
		Company company = companyService.getCompanyById(new Company(), owner.getCompany().getId());
		List<Employee>salesMan = companyService.getActivatedEmployeesByCompanyName(company.getCompanyName());
		List<Contact>contactedPersons = contactService.getAllContactbyCompany(company.getCompanyName());
		List<AppointmentDetails>appointmentDetails = new ArrayList<AppointmentDetails>();
		AppointmentDetails appointmentDetails2 = new AppointmentDetails();
			for (Contact contact : contactedPersons) {
				appointmentDetails2.setContactedPersonId(contact.getId());
				appointmentDetails2.setContactedPersonName(contact.getfName());
			}
			for (Employee employee : salesMan) {
				appointmentDetails2.setSalesManId(employee.getId());
				appointmentDetails2.setSalesManName(employee.getfName());
			}
			
			appointmentDetails.add(appointmentDetails2);
			
			AppointmentDetailsList appointmentDetailsList = new AppointmentDetailsList();
			appointmentDetailsList.setOwnerName(owner.getfName());
			appointmentDetailsList.setAppointmentDetails(appointmentDetails);
		return appointmentDetailsList;
	}
	
	private boolean isAppointmentTimeValid(List<Appointment>calls,Integer inputedStartTime,Integer inputedEndTime,Date inputedDate){
		boolean sucess=true;
		for (Appointment call : calls) {
			String[] startTimeSplit = call.getTime().split(":");
			Integer startTime = (Integer.parseInt(startTimeSplit[0])*60)+
										Integer.parseInt(startTimeSplit[1]);
			
			String[] endTimeSplit = call.getMeetingDuration().split(":");
			Integer endTime = (Integer.parseInt(endTimeSplit[0])*60)+
										Integer.parseInt(endTimeSplit[1]);
			
			long oneDay = 24 * 60 * 60 * 1000;
			long d1 = call.getDate().getTime() / oneDay;
			long d2 = inputedDate.getTime() / oneDay;

					
			if(d1>d2||d1<d2){
				sucess=true;
			}
			if(d1==d2){
				if(inputedStartTime>=endTime && inputedEndTime>inputedStartTime||inputedEndTime<=startTime&&inputedStartTime<inputedEndTime){
					sucess=true;
				}
				else{
					sucess=false;
				}
			}
		}
		return sucess;
	}
	public boolean isValid(Appointment callForm) {
		boolean success = false; 
		String[] startTimeSplit = callForm.getTime().split(":");
		Integer startTime = (Integer.parseInt(startTimeSplit[0])*60)+
									Integer.parseInt(startTimeSplit[1]);
		
		String[] endTimeSplit = callForm.getMeetingDuration().split(":");
		Integer endTime = (Integer.parseInt(endTimeSplit[0])*60)+
									Integer.parseInt(endTimeSplit[1]);
		List<Appointment>appointments = appointmentService.getAppointmentByParentId(callForm.getParentId(), callForm.getParentType());
		boolean isCallTimeValid = isAppointmentTimeValid(appointments, startTime, endTime, callForm.getDate());
		if(isCallTimeValid==false){
			success = false; 
		}
		else{
			success = true; 
		}
		return success;
	}
	
	@RequestMapping(value="/addAppointment",method=RequestMethod.POST,consumes="application/json;charset=UTF-8")
	@ResponseBody
	public Appointment addAppointment(@RequestBody Appointment appointment){
		
		//logger.info("adding new appointment	>>>>>>>>>>>>>>>>>>>>");
		boolean isAppointmentValid = isValid(appointment);
		if(isAppointmentValid==false){
			System.out.println("failure>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			return null;
		}
		else{
			if(appointment.getSalesManId()!=null){
				Employee salesMan = employeeService.getById(appointment.getSalesManId());
				appointment.setSalesMan(salesMan);
			}
			if(appointment.getContactedPersonId()!=null){
				Contact contact = contactService.getContactById(appointment.getContactedPersonId());
				appointment.setContactedPerson(contact);
			}
			appointmentService.addAppointment(appointment);
			calendarService.appointmentEvent(appointment);
			System.out.println("sucess>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			return appointment;
		}
	}
}
